import _ from 'lodash';
import { message } from 'antd';

import { getSubmit, updateState } from '../services/submit';

export default {
  namespace: 'submit',
  state: {
    submitData: [],
  },
  effects: {
    *getSubmits({ payload }, { put }) {
      console.log('[SUBMIT_ID]', payload.id);
      const data = yield getSubmit(payload.id);
      const status = _.get(data, 'status');
      if (Number(status) === 1) {
        console.log('[SUBMIT_STATUS]', status);
        yield put({
          type: 'save',
          payload: {
            submitData: data.reports,
          },
        });
      } else {
        message.error(`获取记录失败:${data.message}`);
      }
      console.log('[SUBMIT_DATA]', data);
    },
    *updateState({ payload }, { put }) {
      const { mode, onEnd } = payload;
      console.log('[SUBMIT_UPDATE_STATE]', payload);
      const data = yield updateState(payload.id, payload.state);
      const status = _.get(data, 'status');
      if (mode === 'remote') {
        if (Number(status) === 1) {
          yield put({
            type: 'getSubmits',
            payload: {
              id: payload.submitId,
            },
          });
          message.success('操作成功');
        } else {
          message.error(data.message);
        }
      } else {
        onEnd(Number(status) !== 1);
      }
    },
  },
  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },
};
